package com.takeaway.ui.activity

import android.annotation.SuppressLint
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.util.Log
import cn.smssdk.EventHandler
import cn.smssdk.SMSSDK
import com.takeaway.R
import com.takeaway.presenter.LoginActivityPresenter
import com.takeaway.utils.TakeOutApplication
import kotlinx.android.synthetic.main.activity_login.*
import org.jetbrains.anko.toast


class LoginActivity : AppCompatActivity() {


    lateinit var loginActivityPresenter: LoginActivityPresenter
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_login)
        loginActivityPresenter = LoginActivityPresenter(this)
        initListener()
    }


    private var isStart = true

    val eh: EventHandler = object : EventHandler() {
        override fun afterEvent(event: Int, result: Int, data: Any?) {
            Log.e("EventHandler", "result = ${result} - data = ${data}")
            if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE) {
//                toast("发送验证码成功")
                handler.sendEmptyMessage(SEND_CODE_SUCCESS)
            } else if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE) {
                // 提交验证码成功
                handler.sendEmptyMessage(SUBMIT_CODE_SUCCESS)
            }
        }
    }

    private fun sendCodeSuccess() {
        isStart = true
        Thread(CodeThread()).start()
        Log.e("login", "发送验验证码")
        tv_user_code.isEnabled = false
        toast("发送验证码成功")
    }

    private fun initListener() {
        iv_user_back.setOnClickListener {
            finish()
        }

        // 获取验证码
        tv_user_code.setOnClickListener {
            val phone = et_user_phone.text.toString()
            Log.e("tv_user_code", "phone = ${phone}")
            if (phone.isEmpty()) {
                toast("电话号码不能为空")
                return@setOnClickListener
            }

            SMSSDK.getVerificationCode("86", phone)
        }

        // 登录
        iv_login.setOnClickListener {
            val phone = et_user_phone.text.toString()
            val code = et_user_code.text.toString()
            SMSSDK.submitVerificationCode("86", phone, code)
//            loginDataSuccess()
//            loginActivityPresenter.loginByPhone("")
        }


        // 注册短信监听
        SMSSDK.registerEventHandler(eh)
    }


    // 登陆成功
    fun loginDataSuccess() {
        val user = TakeOutApplication.user
        user.userId = 100
        finish()
        toast("登录成功")
    }

    // 登录失败
    fun loginFaile() {
        toast("登录失败")
    }


    var handler = @SuppressLint("HandlerLeak")
    object : Handler() {
        override fun handleMessage(msg: Message?) {
            super.handleMessage(msg)
            when(msg?.what) {
                TIME_SUB -> tv_user_code.text = "${timeCount}秒"
                TIME_OUT -> {
                    tv_user_code.text = "重新获取"
                    tv_user_code.isEnabled = true
                    timeCount = 60
                    isStart = false
                }
                SEND_CODE_SUCCESS -> {
                    sendCodeSuccess()
                }
                SUBMIT_CODE_SUCCESS -> {
                    loginDataSuccess()
                }
            }
        }
    }

    companion object {
        val TIME_SUB = -1
        val TIME_OUT = 1
        val SEND_CODE_SUCCESS = 0
        val SUBMIT_CODE_SUCCESS = 2
    }

    var timeCount = 60
    inner class CodeThread: Runnable {
        override fun run() {
            while (isStart && timeCount > 0) {
                Log.e("login", "timeCount = ${timeCount}")
                handler.sendEmptyMessage(TIME_SUB)
                Thread.sleep(1000)
                timeCount --
            }
            handler.sendEmptyMessage(TIME_OUT)
            Log.e("login", "结束")
        }
    }


    override fun onDestroy() {
        super.onDestroy()
        SMSSDK.unregisterEventHandler(eh)
        isStart = false
    }
}
